package ex4.multiThread;

class MyThread7 implements Runnable {
	private int ticket = 5; // 一共有5张票

	@Override
	public void run() {
		for (int x = 0; x < 20; x++) {
			synchronized (this) { // 定义同步代码块
				if (this.ticket > 0) { // 判断当前是否还有剩余票
					try {
						Thread.sleep(1000); // 休眠1秒，模拟延迟
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					System.out.println(Thread.currentThread().getName() + " 卖票，ticket = " + this.ticket--);
				}
			}
		}
	}
}

public class TestDemo7 {
	public static void main(String[] args) throws Exception {
		MyThread7 mt = new MyThread7();
		new Thread(mt, "票贩子A").start(); // 启动多线程
		new Thread(mt, "票贩子B").start(); // 启动多线程
		new Thread(mt, "票贩子C").start(); // 启动多线程
		new Thread(mt, "票贩子D").start(); // 启动多线程
	}
}